package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    BehaviorFeign behaviorFeign;
    /**
     * 保存用户搜索历史记录
     * @param userSearchDto
     */
    @Override
    @Async("taskExecutor")
    public void insert(UserSearchDto userSearchDto) {
        //1 参数检查
        String searchWords = userSearchDto.getSearchWords();
        Integer entryId = userSearchDto.getEntryId();
        //2 查询行为实体
        ResponseResult<ApBehaviorEntry> behaviorResponse = behaviorFeign.findByUserIdOrEquipmentId(entryId, userSearchDto.getEquipmentId());
        if (behaviorResponse.getCode()!=0||behaviorResponse.getData()==null) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"远程调用behaviorFeign.findByUserIdOrEquipmentId出现异常");
        }
        log.info(" 异步保存用户搜索历史记录方法执行啦~ entryId:{}, searchWords:{}", entryId, searchWords);
        //查询当前用户搜索的关键词是否存在
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria
                .where("entryId")
                .is(behaviorResponse.getData().getId())
                .and("keyword")
                .is(userSearchDto.getSearchWords())), ApUserSearch.class);
        //存在则更新时间
        if (apUserSearch!=null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        //3.2 不存在则新增
        apUserSearch = new ApUserSearch();
        apUserSearch.setCreatedTime(new Date());
        apUserSearch.setEntryId(behaviorResponse.getData().getId());
        apUserSearch.setKeyword(searchWords);
        mongoTemplate.save(apUserSearch);
    }

    @Override
    public ResponseResult findUserSearch(UserSearchDto userSearchDto) {
        //1.参数检查
        if (userSearchDto.getMinBehotTime()==null) {
            userSearchDto.setMinBehotTime(new Date());
        }
        if (userSearchDto.getPageSize()<1) {
            userSearchDto.setPageSize(10);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> byUserIdOrEquipmentId = behaviorFeign.findByUserIdOrEquipmentId(user==null?null:user.getId(), userSearchDto.getEntryId());
        if (byUserIdOrEquipmentId.getCode()!=0||byUserIdOrEquipmentId.getData()==null) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"远程调用behaviorFeign.findByUserIdOrEquipmentId出现异常");
        }
        ApBehaviorEntry behaviorEntry = byUserIdOrEquipmentId.getData();
        List<ApUserSearch> searchList = new ArrayList<>();
        if (behaviorEntry!=null) {
            searchList = mongoTemplate.find(Query.query(Criteria
                    .where("entryId")
                    .is(behaviorEntry.getId())
                    .and("createdTime")
                    .lt(userSearchDto.getMinBehotTime()))
                    .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                    .limit(userSearchDto.getPageSize()), ApUserSearch.class);
            return ResponseResult.okResult(searchList);
        }
        return ResponseResult.okResult(searchList);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
        if (historySearchDto.getId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> byUserIdOrEquipmentId = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), historySearchDto.getEquipmentId());
        if (byUserIdOrEquipmentId.getCode()!=0||byUserIdOrEquipmentId.getData()==null) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"远程调用behaviorFeign.findByUserIdOrEquipmentId出现异常");
        }
        ApBehaviorEntry behaviorEntry = byUserIdOrEquipmentId.getData();
        mongoTemplate.remove(Query.query(Criteria.where("id").is(historySearchDto.getId()).and("entryId").is(behaviorEntry.getId())),ApUserSearch.class);
        return ResponseResult.okResult();
    }
}
